﻿<template>
  <a-drawer
    :title="title"
    width="80%"
    :visible="visible1"
    @close="
      () => {
        this.visible1 = false
      }
    "
  >
    <a-card :bordered="false">
      <div class="table-operator">
        <a-button style="margin-bottom: 15px" type="primary" icon="plus" @click="handleAdd()">新建</a-button>
        <a-button
          style="margin-left: 8px"
          type="primary"
          icon="minus"
          @click="handleDelete(selectedRowKeys)"
          :disabled="!hasSelected()"
          :loading="loading"
          >删除
        </a-button>
        <!-- v-if="hasPerm('Cust_CustomerLinkMan.Delete')" -->
        <a-button style="margin-left: 8px" type="primary" icon="redo" @click="getDataList()">刷新</a-button>
        <!-- <a-button type="primary" @click="hanldleLeading()">导入模板</a-button> -->
      </div>

      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="10">
            <a-col :md="4" :sm="24">
              <a-form-item label="查询类别">
                <a-select allowClear v-model="queryParam.Condition">
                  <a-select-option key="Name">姓名</a-select-option>

                  <a-select-option key="Tel_Code">电话</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item>
                <a-input v-model="queryParam.Keyword" placeholder="关键字" />
              </a-form-item>
            </a-col>

            <a-col :md="8" :sm="24">
              <a-button type="primary" @click="inquire">查询 </a-button>
              <a-button style="margin-left: 8px" @click="Repossess">重置</a-button>

              <!-- style="margin-left: 1500px" -->
            </a-col>
            <div class="ImportMoudel">
              <a-button
                style="margin-left: 8px"
                @click="
                  exportExcel(
                    $rootUrl + '/CustomerManagement/Cust_CustomerLinkMan/ExportTemplateToExcel',
                    '客户联系人模板'
                  )
                "
                ><a-icon type="download" />下载模板
              </a-button>
              <a-upload
                name="file"
                :multiple="true"
                :action="
                  $rootUrl +
                    `/CustomerManagement/Cust_CustomerLinkMan/ImportCustomerLinkManToDataBase?CustomerId=${
                      this.row.cCusCode
                    }&&CustomerName=${row.cCusName}`
                "
                :headers="headers"
                @change="handleChange"
              >
                <a-button type="primary" style="margin-left: 8px">
                  <a-icon type="upload" />
                  批量导入
                </a-button>
              </a-upload>
            </div>
          </a-row>
        </a-form>
      </div>

      <!-- <a-modal
        title="导出数据"
        :visible="visible"
        :footer="false"
        @cancel="visible = false"
        width="360px"
        style="text-align: center"
      >
        <a-button style="margin: 0 10px" @click="outTab" type="primary">导出当前数据</a-button>
        <a-button @click="openhtml" type="primary" style="margin-left: 8px">
          <a-icon type="primary" />
          导出所有数据
        </a-button>
      </a-modal> -->
      <a-table
        id="tables"
        ref="table"
        :scroll="{ y: 530, x: 1000 }"
        :columns="columns"
        :rowKey="(row, index) => index"
        :dataSource="data"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :bordered="true"
        size="small"
      >
        <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record.Id)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDelete([record.Id])">删除</a>
          </template>
        </span>
      </a-table>
      <leading-show
        ref="leadingShow"
        :parentObj="this"
        leading="/CustomerManagement/Cust_CustomerLinkMan/Import"
        templet="/CustomerManagement/Cust_CustomerLinkMan/ExportToExcel"
      ></leading-show>

      <edit-form :row="row" ref="editForm" :parentObj="this"></edit-form>
    </a-card>
  </a-drawer>
</template>

<script>
function exportExcel(res, title) {
  let data = res.data || res || {}

  const blob = new Blob([data], {
    type: 'application/vnd.ms-excel' //设置为excel格式
  })
  const url = window.URL.createObjectURL(blob)
  const fileName = title
  const aTag = document.createElement('a')
  aTag.download = fileName
  aTag.href = url
  aTag.click()
  URL.revokeObjectURL(aTag.href)
  // v.$message.success("导出成功!");
}

import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import Token from '@/utils/cache/TokenCache'
import { download } from '@/components/download'
import EditForm from './EditForm'
import leadingShow from './leadingShow.vue'
import moment from 'moment'

const columns = [
  { title: '姓名', dataIndex: 'Name', width: '80px' },
  { title: '组织机构', dataIndex: 'Department', width: '90px' },
  { title: '职位', dataIndex: 'Position', width: '90px' },
  { title: '公司', dataIndex: 'CustomerName', width: '120px' },

  { title: '详细地址', dataIndex: 'Address', width: '200px' },
  { title: '电话', dataIndex: 'Tel_Code', width: '110px' },

  { title: '角色名称', dataIndex: 'RoleName', width: '90px' },
  { title: '备注', dataIndex: 'Remark', width: '250px' },
  {
    title: '操作',
    fixed: 'right',
    dataIndex: 'action',
    align: 'left',
    scopedSlots: { customRender: 'action' },
    width: '100px'
  }
]

export default {
  components: {
    EditForm,
    leadingShow,
    Token
  },
  mounted() {
    this.getDataList()
    this.getlist()
  },
  data() {
    return {
      visible1: false,
      visible: false,
      headers: {
        authorization: 'Bearer ' + Token.getToken()
      },
      title: '',
      row: {},
      data: [],
      list: [], //省级
      listChildren: [], //市
      county: [], //县
      CustomerId: '',
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'Id', order: 'desc' },
      loading: false,
      columns,
      id: '',
      queryParam: { Condition: 'Name' },
      selectedRowKeys: []
    }
  },

  methods: {
    inquire() {
      this.pagination.current = 1
      // this.queryParam.Condition = this.Condition
      // this.queryParam.Keyword = this.Keyword

      this.getDataList()
    },
    Repossess() {
      this.pagination.current = 1
      this.queryParam = { Condition: 'Name' }
      this.getDataList()
    },
    //市级change
    city(e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=' + e, {}).then(resJson => {
        this.loading = false
        this.listChildren = resJson.Data
      })
    },

    //县change
    village(e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=' + e, {}).then(resJson => {
        this.loading = false

        this.county = resJson.Data
      })
    },
    //获取省份信息
    getlist(e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=0', {}).then(resJson => {
        this.loading = false
        this.list = resJson.Data

        // this.getlistUser()
      })
    },
    //导出当前数据
    outTab() {
      /* generate workbook object from table */
      let wb = XLSX.utils.table_to_book(document.querySelector('#tables'))
      /* get binary string as output */
      let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '客户联系人.xls')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    // 导出全部数据
    openhtml() {
      this.$http({
        url: '/CustomerManagement/Cust_CustomerLinkMan/ExportCustomerLinkMan',
        method: 'post',
        data: {
          PageIndex: this.pagination.current,
          PageRows: 999,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order, DeptId: this.DeptId,
          Search: [this.queryParam]
        },
        responseType: 'blob'
      }).then(resJson => {
        exportExcel(resJson, '客户联系人信息')
      })
    },

    exportExcel(url, tit) {
      download(url, tit)
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getDataList()
    },
    getDataList() {
      this.selectedRowKeys = []

      // this.loading = true
      this.$http
        .post('/CustomerManagement/Cust_CustomerLinkMan/GetDataListByConditions', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order, DeptId: this.DeptId,
          Search: [
            {
              Condition: 'CustomerId',
              Keyword: this.id
            },
            {
              Condition: this.queryParam.Condition,
              Keyword: this.queryParam.Keyword
            }
          ],
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          this.CustomerId = this.data.CustomerId
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    hanldleLeading() {
      this.$refs.leadingShow.openForm(null, '客户信息')
    },
    init() {
      this.visible1 = true
    },
    openForm(row, title) {
      this.init()
      this.title = title
      this.row = row

      if (row) {
        this.id = row.cCusCode
        // this.cCusName = row.cCusName
        this.loading = true
        this.$http
          .post('/CustomerManagement/Cust_CustomerLinkMan/GetDataListByConditions', {
            PageIndex: this.pagination.current,
            PageRows: 999,
            SortField: this.sorter.field || 'Id',
            SortType: this.sorter.order, DeptId: this.DeptId,
            Search: [
              {
                Condition: 'CustomerId',
                Keyword: row.cCusCode
              }
            ],
            ...this.filters
          })
          .then(resJson => {
            this.loading = false
            this.data = resJson.Data
            if (this.data) {
              const pagination = { ...this.pagination }
              pagination.total = resJson.Total
              this.pagination = pagination
            }
          })
      }
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    handleAdd() {
      this.$refs.editForm.openForm(null, '新建客户联系人信息')
    },
    // 导入文件类型
    handleChange(info) {
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        if (info.file.response.Success === false) {
          this.$message.error(`${info.file.name}文件,${info.file.response.Msg},请检查文件内容！ `)
        } else {
          this.$message.success(`${info.file.name}  文件上传成功！`)
          this.getDataList()
        }
        this.visible = false
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败！`)
      }
    },
    handleEdit(id) {
      this.$refs.editForm.openForm(id, '编辑客户联系人信息')
    },
    handleDelete(ids) {
      var thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
       return new Promise((resolve, reject) => {
          thisObj.$http.post('/CustomerManagement/Cust_CustomerLinkMan/DeleteData', ids).then(resJson => {
            resolve()
            if (resJson.Success) {
              thisObj.$message.success('操作成功!')
              thisObj.getDataList()
            } else {
              thisObj.$message.error(resJson.Msg)
            }
          })
        })
      })
      
    },
    timeFormat(val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD HH:mm')
    }
  }
}
</script>

<style scoped>
.ImportMoudel {
  float: right;
  display: flex;
  align-items: center;
}
</style>
